import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { DESCRIPTION_MODULE, Features, getLocalStorage, I18NService, LOCAL_STORAGE_KEY, setLocalStorage, USER_TYPE } from '@shared';
import { MenuItem, ModalService, OptionItem } from '@iux/live';
import { AppContentRouter } from './app-content.router';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-app-content',
  templateUrl: './app-content.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.live-design-content]': 'true',
  },
})
export class AppContentComponent implements OnInit {
  MENU_ICON = {
    components: 'assets/images/site/menu-components.svg',
    foundation: 'assets/images/site/menu-foundation.svg',
    develop: 'assets/images/site/menu-develop.svg',
    overview: 'assets/images/site/menu-overview.svg',
    pattern: 'assets/images/site/menu-pattern.svg',
    'join-us': 'assets/images/site/menu-components.svg', // TODO 替换
    'pro-components': 'assets/images/site/menu-resource.svg',
  };
  DEFAULT_VERSION = { key: '3.0', label: '3.0', isLeaf: true };

  routers = [];
  menus: MenuItem[] = [];
  activeId;

  selectedFrame: OptionItem;
  frameData: OptionItem[] = [
    { key: 'angular', label: 'Angular', imgUrl: 'assets/images/site/angular-icon.png', isLeaf: true },
    { key: 'react', label: 'React', imgUrl: 'assets/images/site/react-icon.png', isLeaf: true },
  ];

  selectedVersion: OptionItem = this.DEFAULT_VERSION;
  versionData: OptionItem[];
  versionConfig = {
    angular: [
      { key: '1.0', label: '1.0', url: '', isLeaf: true },
      { key: '2.0', label: '2.0', url: '', isLeaf: true },
      { key: '3.0', label: '3.0', isLeaf: true },
      { key: '3.0-Pro', label: '3.0高阶组件', url: '', isLeaf: true },
    ],
    react: [{ key: '3.0', label: '3.0', url: '', isLeaf: true }],
  };

  selectedCharacter: string;
  initCharacter: string;
  characterData: OptionItem[] = [
    { key: USER_TYPE.DEVELOPER, label: '开发者', isLeaf: true },
    { key: USER_TYPE.DESIGNER, label: '设计师', isLeaf: true },
  ];
  USER_TYPE = USER_TYPE;

  visible = false;
  searchValue = '';
  searchTimer: any;
  searchResultData = { components: [], icons: [] }; // 预留搜索icon
  noNeedToBeSearched = ['overview', 'join-us', 'develop']; // 不需要被搜索到的路由

  isDarkTheme = false;
  private selectMenuItemPath: string;

  @ViewChild('characterSelectorTpl') characterSelectorTpl: TemplateRef<any>;

  constructor(
    private router: Router,
    private i18n: I18NService,
    private cdr: ChangeDetectorRef,
    private modalService: ModalService,
    private titleService: Title
  ) {}

  ngOnInit(): void {
    this.activeId = this.getActiveId();
    this.selectedFrame = this.frameData[0];
    this.versionData = this.versionConfig[this.selectedFrame.key];
    this.initCharacter = getLocalStorage(LOCAL_STORAGE_KEY.LIVE_USER_TYPE);
    this.selectedCharacter = this.initCharacter || USER_TYPE.DEVELOPER;
    
    if (!this.initCharacter) {
      setTimeout(() => {
        this.openCharacterModal();
      });
    }

    this.initMenus();
    this.setTheme();
    this.titleService.setTitle(this.getTitle(this.menus, this.router.url));

    this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((navigation: NavigationEnd) => {
      this.activeId = this.getActiveId();
      this.setTheme();
      if (this.selectMenuItemPath !== navigation.url) {
        this.titleService.setTitle(this.getTitle(this.menus, navigation.url));
        (window as any).hwa?.('trackPageView');
        this.selectMenuItemPath = navigation.url;
      }
    });
  }

  openCharacterModal(): void {
    this.initCharacter =  USER_TYPE.DEVELOPER;
    this.modalService.create({
      lvContent: this.characterSelectorTpl,
      lvHeader: '请选择您的角色',
      lvWidth: 480,
      lvHeight: 306,
      lvCloseButtonDisplay: false,
      lvCancelText: null,
      lvOk: () => {
        this.changeCharacter(this.selectedCharacter);
      },
    });
  }

  initMenus(): void {
    this.routers = AppContentRouter.slice(0);
    this.menus = [
      { id: 'develop', label: this.i18n.get('develop'), items: this.getMenuItems('develop') },
      {
        id: 'components',
        label: this.i18n.get('components'),
        items: this.getComponentsMenus(),
      },
    ];
  }

  // 通过menus中的routerlink获取当前页面的label
  getTitle(menus: MenuItem[], url: string): string {
    let pageTitle;
    const getMenuItemLabel = (menu: MenuItem[]) => {
      for (const child of menu) {
        if (child.routerLink && child.routerLink.includes(url)) {
          pageTitle = child.label;
          return;
        }
        if (child.items && !child.routerLink) {
          getMenuItemLabel(child.items);
        }
      }
    };
    getMenuItemLabel(menus);
    return `${pageTitle}-LIVE Design`;
  }

  getComponentsMenus(): MenuItem[] {
    return [
      {
        id: 'general',
        label: this.i18n.get('general'),
        type: 'group',
        items: this.getMenuItems('general', 'components'),
        expanded: true,
      },
      {
        id: 'navigator',
        label: this.i18n.get('navigator'),
        type: 'group',
        items: this.getMenuItems('navigator', 'components'),
      },
      {
        id: 'dataEntry',
        label: this.i18n.get('dataEntry'),
        type: 'group',
        items: this.getMenuItems('dataEntry', 'components'),
      },
      {
        id: 'dataDisplay',
        label: this.i18n.get('dataDisplay'),
        type: 'group',
        items: this.getMenuItems('dataDisplay', 'components'),
      },
      {
        id: 'feedBack',
        label: this.i18n.get('feedBack'),
        type: 'group',
        items: this.getMenuItems('feedBack', 'components'),
      },
      {
        id: 'others',
        label: this.i18n.get('others'),
        type: 'group',
        items: this.getMenuItems('others', 'components'),
      },
      {
        id: 'visualization',
        label: this.i18n.get('visualization'),
        type: 'group',
        items: this.getMenuItems('visualization', 'components'),
      },
    ];
  }

  getActiveId(): string {
    const arr = this.router.url.split('/');
    return `${arr[arr?.length - 2]}-${arr[arr?.length - 1]}`;
  }

  getMenuItems(type: string, routerPath?: string): MenuItem[] {
    return this.routers
      .filter(router => router.type === type)
      .map(router => {
        const newRouter = { ...{}, ...router };
        newRouter.label = this.getMenuLabel(router.path, router.type);

        if (routerPath) {
          newRouter.id = `${routerPath}-${router.path}`;
          newRouter.routerLink = [`/${routerPath}/${router.path}`];
        } else {
          newRouter.id = `${router.type}-${router.path}`;
          newRouter.routerLink = [`/${router.type}/${router.path}`];
        }

        const feature = Features.find(({ path }) => path.endsWith(router.path));
        if (feature?.type) {
          newRouter.featureType = feature.type;
        }

        return newRouter;
      });
  }

  getMenuLabel(value: string, type?: string): string {
    let label = '';
    if (!type || !DESCRIPTION_MODULE.includes(type)) {
      label = value;
    } else {
      label = `${type}-${value}`;
    }
    return `${this.i18n.get(label)[0]} ${this.i18n.get(label)[1]}`;
  }

  changeFrame(e): void {
    this.versionData = [...this.versionConfig[e.key]];
    // react 只有一个版本，直接跳转
    if (e.key === 'react') {
      window.location.href = this.versionData.find(item => item.key === this.selectedVersion.key).url;
    }
  }

  changeVersion(version: OptionItem): void {
    const { key } = this.selectedFrame || {};

    if (key === 'angular' && version.key === '3.0') {
      return;
    }

    window.open(version.url);
    this.selectedVersion = { ...this.DEFAULT_VERSION };
  }

  changeCharacter(val: string): void {
    setLocalStorage(LOCAL_STORAGE_KEY.LIVE_USER_TYPE, val);
    if (this.initCharacter !== val) {
      window.location.reload();
    }
  }

  setTheme(): void {
    const nav = this.router.url.split('/')[1];
    if (nav === 'overview') {
      this.isDarkTheme = true;
    }
  }

  search(value: string): void {
    if (!value) {
      this.visible = false;
    }

    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
      this.searchTimer = null;
    }

    this.searchTimer = setTimeout(() => {
      this.searchResultData = { components: [], icons: [] };

      // 修改为搜索国际化
      const router = AppContentRouter.filter(item => item.type && !this.noNeedToBeSearched.includes(item.type));
      const searchableItems = router.map(item => ({
        key: item.name || item.path,
        label: this.getMenuLabel(item.path, item.type),
        value: { ...item },
      }));

      // 搜索组件
      const components = searchableItems.filter(item => item.label.toLowerCase().indexOf(value.toLocaleLowerCase()) >= 0);
      this.searchResultData.components = value ? components.map(item => item.value) : [];

      if (value) {
        this.visible = true;
      }

      this.cdr.detectChanges();
    }, 200);
  }

  searchResultClick(event, item): void {
    if (!item.path) {
      event.preventDefault();
      return;
    }

    let routerLink;
    if (DESCRIPTION_MODULE.indexOf(item.type) > -1 && item.type !== 'visualization') {
      routerLink = [`/${item.type}/${item.path}`];
    } else {
      routerLink = [`/components/${item.path}`];
    }

    this.router.navigate(routerLink).then(() => {
      this.searchValue = '';
      this.visible = false;
    });
  }

  goHome(): void {
    this.router.navigate(['/home']);
  }
}
